﻿using AutoMapper;
using B.S.Traceable.Domain.Entitiy;
using B.S.Traceable.ErrorCode;
using B.S.Traceable.Infrasturcture.Interfaces;
using B.S.Traceable.Read.Api.Application.Command.Traceable;
using B.S.Traceable.Read.Api.Dtos;
using MediatR;
using Microsoft.VisualBasic;

namespace B.S.Traceable.Read.Api.Application.CommandHandler.Traceable
{
    public class GetTraceableHandler : IRequestHandler<GetTraceableCommand, ApiPaging<TraceableDto>>
    {

        private readonly IBaseRepository<TraceableModel> traRepo;
        private readonly IMapper mapper;
        private readonly IBaseRepository<ShopModel> shopRepo;

        public GetTraceableHandler(IBaseRepository<TraceableModel> traRepo, IMapper mapper, IBaseRepository<ShopModel> shopRepo)
        {
            this.traRepo = traRepo;
            this.mapper = mapper;
            this.shopRepo = shopRepo;
        }

        public Task<ApiPaging<TraceableDto>> Handle(GetTraceableCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<TraceableDto> result=new ApiPaging<TraceableDto>();
            result.Code = ApiEnums.Success;
            result.Msg = "查询成功";

            var model = from a in traRepo.GetAll()
                        join b in shopRepo.GetAll() on a.ShopId equals b.ShopId
                        where a.IsDeleted == false
                        select new TraceableDto
                        { 
                            TraceableId=a.TraceableId,
                            ShopId=b.ShopId,
                            ShopName=b.ShopName,
                            Production_batches=a.Production_batches,
                            Shelf_Life=a.Shelf_Life,
                            Production_License_Number= a.Production_License_Number,
                            Production_Industry=a.Production_Industry,
                            Picture = a.Picture,
                            Information=a.Information,
                            CreateName=a.CreateName,
                            CreateTime=a.CreateTime,
                            UpdateName=a.UpdateName,
                            UpdateTime=a.UpdateTime,
                        };

            result.TotalCount = model.Count();
            result.TotalPage = (int)Math.Ceiling((result.TotalCount*1.0)/request.PageSize);
            model=model.OrderBy(x=>x.TraceableId).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize);
            result.Item = mapper.Map<List<TraceableDto>>(model);
            return Task.FromResult(result);
        }
    }
}
